package com.hospital.hospitalsystem.modules.hospital.biz;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.hospital.hospitalsystem.base.PageData;
import com.hospital.hospitalsystem.entity.QuartzExt;
import com.hospital.hospitalsystem.modules.doctor.dao.entity.DoctorIntroduceEntity;
import com.hospital.hospitalsystem.modules.doctor.service.DoctorIntroduceService;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.DepartmentEntity;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.DoctorOrderEntity;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.DoctorPriceEntity;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.QuartzCronEntity;
import com.hospital.hospitalsystem.modules.hospital.dto.*;
import com.hospital.hospitalsystem.modules.hospital.service.DepartmentService;
import com.hospital.hospitalsystem.modules.hospital.service.DoctorOrderService;
import com.hospital.hospitalsystem.modules.hospital.service.DoctorPriceService;
import com.hospital.hospitalsystem.modules.hospital.service.QuartzCronService;
import com.hospital.hospitalsystem.modules.hospital.task.DoctorOrderDetail;
import com.hospital.hospitalsystem.modules.login.dao.entity.DoctorEntity;
import com.hospital.hospitalsystem.modules.login.dao.entity.HospitalMessageEntity;
import com.hospital.hospitalsystem.modules.login.dao.entity.UserEntity;
import com.hospital.hospitalsystem.modules.login.service.DoctorService;
import com.hospital.hospitalsystem.modules.login.service.HospitalMessageService;
import com.hospital.hospitalsystem.modules.login.service.UserService;
import com.hospital.hospitalsystem.utils.QuartzManageUtils;
import com.sun.corba.se.spi.orbutil.threadpool.Work;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.CharRange;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobDataMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.print.Doc;
import java.time.DayOfWeek;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author qiancheng@cqxyy.net
 * @date 2023/2/22
 */
@Service
public class HospitalBiz {

    @Autowired
    private DoctorPriceService doctorPriceService;

    @Autowired
    private DoctorOrderService doctorOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private QuartzCronService quartzCronService;

    @Autowired
    private QuartzManageUtils quartzManageUtils;

    @Autowired
    private DoctorIntroduceService doctorIntroduceService;

    @Autowired
    private HospitalMessageService hospitalMessageService;

    /**
     * 添加部门配置
     * @param req
     */
    public void departmentAdd(AddDepartmentReq req) {
        checkDepartment(req.getHospitalUuid(),req.getCode(),req.getName());
        DepartmentEntity departmentEntity = new DepartmentEntity();
        BeanUtils.copyProperties(req,departmentEntity);
        departmentService.insertSelective(departmentEntity);
    }

    /**
     * 检查部门配置
     * @param hospitalUuid
     * @param code
     */
    public void checkDepartment(String hospitalUuid,String code,String name){
        Example example = new Example(DepartmentEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("hospitalUuid",hospitalUuid);
        criteria.andEqualTo("code",code);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andEqualTo("hospitalUuid",hospitalUuid);
        criteria1.andEqualTo("name",name);
        example.or(criteria1);
        List<DepartmentEntity> list = departmentService.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)){
            throw new RuntimeException("此代码/部门已存在");
        }
    }

    /**
     * 查看部门列表
     * @param req
     * @return
     */
    public PageData<DepartmentRsp> departmentList(DepartmentListReq req) {
        Example example = new Example(DepartmentEntity.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(req.getName())){
            criteria.andLike("name","%" + req.getName() + "%");
        }
        if (StringUtils.isNotBlank(req.getHospitalUuid())){
            criteria.andEqualTo("hospitalUuid",req.getHospitalUuid());
        }else{
            throw new RuntimeException("医院UUID为空");
        }
        com.github.pagehelper.Page<DepartmentRsp> page = PageHelper.startPage(
                req.getCurrentPage(), req.getPageSize()
        );
        List<DepartmentRsp> list = departmentService.selectByExample(example).stream().map(s ->{
            DepartmentRsp departmentRsp = new DepartmentRsp();
            BeanUtils.copyProperties(s,departmentRsp);
            return departmentRsp;
        }).collect(Collectors.toList());
        int longs = ((Number) page.getTotal()).intValue();
        PageData<DepartmentRsp> pageData = PageData.of(list,page.getPageNum(),page.getPageSize(),longs);
        return pageData;
    }

    /**
     * 根据id删除部门配置
     * @param id
     */
    @Transactional
    public void departmentDelete(Long id) {
        DepartmentEntity departmentEntity = departmentService.selectByPrimaryKey(id);
        Example example = new Example(DoctorEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("hospitalUuid",departmentEntity.getHospitalUuid());
        criteria.andEqualTo("department",departmentEntity.getCode());
        List<DoctorEntity> list = doctorService.selectByExample(example);
        if (CollectionUtils.isNotEmpty(list)) {
            throw new RuntimeException("此部门还存在医生归属,请修改相应医生后重试");
        }
        departmentService.deleteByPrimaryKey(id);
    }

    /**
     * 添加医生
     * @param req
     */
    @Transactional
    public void doctorAdd(DoctorAddReq req) {
        Example example = new Example(DoctorEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("account",req.getAccount()).andEqualTo("hospitalUuid",req.getHospitalUuid())
                .andNotEqualTo("isDelete",3);
        List<DoctorEntity> list = doctorService.selectByExample(example);
        String doctorUuid = UUID.randomUUID().toString();
        if (CollectionUtils.isNotEmpty(list)){
            throw new RuntimeException("医生账户不允许重复");
        }
        if (req.getType().equals("doctor")) {
            //检查工作时间是否冲突
            Map<Integer,List<TimeRangeExt>> check = req.getWorks().stream().collect(Collectors.toMap(s->s.getDay(),s-> {
                List<TimeRangeExt> tmp = new ArrayList<>();
                s.getTimes().forEach(item -> {
                    TimeRangeExt timeRangeExt = new TimeRangeExt();
                    timeRangeExt.setStartTime(item.getStartAndEndTime().get(0));
                    timeRangeExt.setEndTime(item.getStartAndEndTime().get(1));
                    tmp.add(timeRangeExt);
                });
                return tmp;
            }));
            boolean flag = false;
            for (Map.Entry<Integer,List<TimeRangeExt>> entry : check.entrySet()) {
                flag = hasTimeConflict(entry.getValue());
                if (flag) {
                    break;
                }
            }
            if (flag) {
                throw new RuntimeException("填写的工作时间冲突,请检查");
            }
        }
        DoctorEntity doctorEntity = new DoctorEntity();
        doctorEntity.setUuid(doctorUuid);
        BeanUtils.copyProperties(req,doctorEntity);
        doctorEntity.setStatus(2);
        doctorEntity.setIsDelete(1);
        doctorService.insertSelective(doctorEntity);

        if(req.getType().equals("doctor")){
            //创建医生个人信息表
            DoctorIntroduceEntity doctorIntroduceEntity = new DoctorIntroduceEntity();
            doctorIntroduceEntity.setDoctorUuid(doctorEntity.getUuid());
            doctorIntroduceEntity.setHospitalUuid(req.getHospitalUuid());
            doctorIntroduceEntity.setStatus(1);
            doctorIntroduceService.insertSelective(doctorIntroduceEntity);
        }
        UserEntity user = new UserEntity();
        user.setUuid(doctorUuid);
        user.setPassword(req.getPassword());
        user.setAccount(req.getAccount());
        user.setType(req.getType());
        Map<String,String> tmp = new HashMap<>();
        tmp.put("hospitalUuid",req.getHospitalUuid());
        user.setExt(JSONObject.toJSONString(tmp));
        userService.insertSelective(user);
        if (req.getType().equals("doctor")){
            DoctorPriceEntity doctorPriceEntity = new DoctorPriceEntity();
            doctorPriceEntity.setDoctorUuid(doctorUuid);
            doctorPriceEntity.setPrice(req.getPrice());
            doctorPriceEntity.setHospitalUuid(req.getHospitalUuid());
            doctorPriceService.insertSelective(doctorPriceEntity);
            for (WorkDayExt workDay : req.getWorks()){
                int day = workDay.getDay();
                if (CollectionUtils.isNotEmpty(workDay.getTimes())){
                    for (WorkTimeExt workTime : workDay.getTimes()){
                        DoctorOrderEntity doctorOrderEntity = new DoctorOrderEntity();
                        doctorOrderEntity.setDoctorUuid(doctorUuid);
                        doctorOrderEntity.setHospitalUuid(req.getHospitalUuid());
                        doctorOrderEntity.setDay(day);
                        doctorOrderEntity.setStartTime(workTime.getStartAndEndTime().get(0));
                        doctorOrderEntity.setEndTime(workTime.getStartAndEndTime().get(1));
                        doctorOrderEntity.setTotal(workTime.getTotal());
                        doctorOrderService.insertSelective(doctorOrderEntity);
                    }
                }
            }
        }
    }

    /**
     * 查找医生列表
     * @param req
     * @return
     */
    public PageData<DoctorListRsp> doctorList(DoctorListReq req) {
        Example example = new Example(DoctorEntity.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isBlank(req.getHospitalUuid())){
            throw new RuntimeException("医院UUID不存在");
        }
        com.github.pagehelper.Page<DoctorListRsp> page = PageHelper.startPage(
                req.getCurrentPage(), req.getPageSize()
        );
        List<DoctorListRsp> result = doctorService.selectDoctorList(req);

        List<String> codes = result.stream().map(DoctorListRsp::getDepartment).collect(Collectors.toList());
        Example exampleDepartment = new Example(DepartmentEntity.class);
        Example.Criteria criteriaDepartment = exampleDepartment.createCriteria();
        criteriaDepartment.andEqualTo("hospitalUuid",req.getHospitalUuid());
        if(CollectionUtils.isNotEmpty(codes)){
            criteriaDepartment.andIn("code",codes);
        }
        Map<String,String> codeMap = departmentService.selectByExample(exampleDepartment).stream().collect(Collectors.toMap(DepartmentEntity::getCode,DepartmentEntity::getName));
        result.forEach(s ->{
            s.setDepartment(codeMap.get(s.getDepartment()));
        });
        int longs = ((Number) page.getTotal()).intValue();
        PageData<DoctorListRsp> pageData = PageData.of(result,page.getPageNum(),page.getPageSize(),longs);
        return pageData;
    }

    /**
     * 设置医生下一周工作时间 定时任务 -- 开
     * @param req
     */
    public void setWorkTime(DoctorOrderDetailReq req) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(req.getDayTime());
        //Calendar.HOUR为12小时制,HOUR_OF_DAY为24小时制
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int minutes = calendar.get(Calendar.MINUTE);
        int seconds = calendar.get(Calendar.SECOND);
        //拼接cron表达式 cron表达式1代表星期日，2-7代表星期一至星期六
        Integer weekDay;
        weekDay = req.getWeekDay() == 7 ? 1 : req.getWeekDay() + 1;

        String cron = seconds + " " + minutes + " " + hours + " ? " + "* " + weekDay;
        startTask(req.getHospitalUuid(),cron);
        //更改状态
        QuartzCronEntity quartzCronEntity = new QuartzCronEntity();
        quartzCronEntity.setDayTime(req.getDayTime());
        quartzCronEntity.setWeekDay(req.getWeekDay());
        quartzCronEntity.setStatus(req.getStatus());
        Example exampleQuartzCron = new Example(QuartzCronEntity.class);
        Example.Criteria criteriaQuartzCron = exampleQuartzCron.createCriteria();
        criteriaQuartzCron.andEqualTo("hospitalUuid",req.getHospitalUuid());
        quartzCronService.updateByExampleSelective(quartzCronEntity,exampleQuartzCron);
    }

    /**
     * 停止定时任务
     * @param
     */
    public void stopTask(String hospitalUuid) {
        //关闭定时任务
        quartzManageUtils.removeJob(getQuartzExt(hospitalUuid, null));
        //更改状态
        QuartzCronEntity quartzCronEntity = new QuartzCronEntity();
        quartzCronEntity.setStatus(1);
        Example exampleQuartzCron = new Example(QuartzCronEntity.class);
        Example.Criteria criteriaQuartzCron = exampleQuartzCron.createCriteria();
        criteriaQuartzCron.andEqualTo("hospitalUuid",hospitalUuid);
        quartzCronService.updateByExampleSelective(quartzCronEntity,exampleQuartzCron);
    }
    /**
     * 执行定时
     * @param hospital
     */
    public void startTask(String hospital,String cron){
        // 获取定时任务需要的参数
        QuartzExt quartzDTO = getQuartzExt(hospital, cron);
        //根据定时策略添加任务
        quartzManageUtils.addCronJob(quartzDTO);
    }


    /**
     * 根据参数定时执行医生值班
     *
     * @param hospitalUuid 医院uuid
     * @param cron   定时策略
     * @return {@link QuartzExt}
     */
    private QuartzExt getQuartzExt(String hospitalUuid, String cron) {
        QuartzExt dto = new QuartzExt();
        String scriptType = "JOB";
        dto.setJobName(scriptType + "@" + hospitalUuid);
        dto.setJobGroupName(scriptType + "_GROUP@"  + "@" + hospitalUuid);
        dto.setTriggerName(scriptType + "_TRIGGER@" + hospitalUuid);
        dto.setTriggerGroupName(scriptType + "_TRIGGER_GROUP@" + "@" + hospitalUuid);

        if (StringUtils.isNotBlank(cron)) {
            dto.setCron(cron);
        }
        dto.setJobClass(DoctorOrderDetail.class);
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("hospitalUuid",hospitalUuid);
        dto.setJobDataMap(new JobDataMap(paramsMap));
        return dto;
    }

    /**
     * 根据id编辑部门配置
     * @param req
     */
    public void editDepartment(DepartmentReq req) {
        DepartmentEntity department = departmentService.selectByPrimaryKey(req.getId());
        Example example = new Example(DepartmentEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteria.andEqualTo("code",req.getCode());
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteria1.andEqualTo("name",req.getName());
        example.or(criteria1);
        List<DepartmentEntity> list = departmentService.selectByExample(example);
        if (list.size() == 1){
            DepartmentEntity departmentEntity = list.get(0);
            if (!departmentEntity.getCode().equals(department.getCode()) && !departmentEntity.getName().equals(department.getName())){
                throw new RuntimeException("此代码/部门已存在");
            }
        }
        if (list.size() > 1){
            throw new RuntimeException("此代码/部门已存在");
        }
        DepartmentEntity departmentEntity = new DepartmentEntity();
        BeanUtils.copyProperties(req,departmentEntity);
        departmentService.updateByPrimaryKey(departmentEntity);
        //如果已经有医生在这个部门，则修改时会影响所有医生的部门状态
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("department",department.getCode());
        DoctorEntity doctorEntity = new DoctorEntity();
        doctorEntity.setDepartment(departmentEntity.getCode());
        doctorService.updateByExampleSelective(doctorEntity,exampleDoctor);
    }

    /**
     * 根据uuid获取医生信息
     * @param req
     * @return
     */
    @Transactional
    public DoctorRsp doctorGet(DoctorGetReq req) {
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("uuid",req.getDoctorUuid());
        List<DoctorEntity> list = doctorService.selectByExample(exampleDoctor);

        Example exampleDepartment = new Example(DepartmentEntity.class);
        Example.Criteria criteriaDepartment = exampleDepartment.createCriteria();
        criteriaDepartment.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDepartment.andEqualTo("code",list.get(0).getDepartment());
        List<DepartmentEntity> departmentEntities = departmentService.selectByExample(exampleDepartment);
        list.get(0).setDepartment(departmentEntities.get(0).getName());
        DoctorRsp doctorRsp = new DoctorRsp();
        BeanUtils.copyProperties(list.get(0),doctorRsp);
        return doctorRsp;
    }

    /**
     * 更新医生信息
     * @param req
     */
    @Transactional
    public void doctorUpdate(DoctorAddReq req) {
        if (req.getStatus() == 1) {
            throw new RuntimeException("请先下线此医生后再尝试修改");
        }
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andNotEqualTo("uuid",req.getDoctorUuid());
        criteriaDoctor.andEqualTo("account",req.getAccount());
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        criteriaDoctor.andIn("isDelete",arrayList);
        List<DoctorEntity> listDoctor = doctorService.selectByExample(exampleDoctor);
        if (CollectionUtils.isNotEmpty(listDoctor)) {
            throw new RuntimeException("医生账户不允许重复");
        }
        //医生表
        exampleDoctor = new Example(DoctorEntity.class);
        criteriaDoctor = exampleDoctor.createCriteria();
        DoctorEntity doctorEntity = new DoctorEntity();
        doctorEntity.setName(req.getName());
        doctorEntity.setSex(req.getSex());
        doctorEntity.setPicture(req.getPicture());
        doctorEntity.setDepartment(req.getDepartment());
        doctorEntity.setAccount(req.getAccount());
        doctorEntity.setPassword(req.getPassword());
        doctorEntity.setType(req.getType());
        doctorEntity.setPictureName(req.getPictureName());
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("uuid",req.getDoctorUuid());
        doctorService.updateByExampleSelective(doctorEntity,exampleDoctor);

        //用户登录表
        Example exampleUser = new Example(UserEntity.class);
        Example.Criteria criteriaUser = exampleUser.createCriteria();
        criteriaUser.andEqualTo("uuid",req.getDoctorUuid());
        criteriaUser.andCondition("ext -> '$.hospitalUuid' = \"" + req.getHospitalUuid() + "\"");
        UserEntity userEntity = new UserEntity();
        userEntity.setAccount(req.getAccount());
        userEntity.setPassword(req.getPassword());
        userEntity.setType(req.getType());
        userService.updateByExampleSelective(userEntity,exampleUser);

        //医生单价表
        Example exampleDoctorPrice = new Example(DoctorPriceEntity.class);
        Example.Criteria criteriaDoctorPrice = exampleDoctorPrice.createCriteria();
        criteriaDoctorPrice.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctorPrice.andEqualTo("doctorUuid",req.getDoctorUuid());
        doctorPriceService.deleteByExample(exampleDoctorPrice);

        //医生预约信息表
        Example exampleDoctorOrder = new Example(DoctorOrderEntity.class);
        Example.Criteria criteriaDoctorOrder = exampleDoctorOrder.createCriteria();
        criteriaDoctorOrder.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctorOrder.andEqualTo("doctorUuid",req.getDoctorUuid());
        doctorOrderService.deleteByExample(exampleDoctorOrder);
        if (req.getType().equals("doctor")) {
            DoctorPriceEntity doctorPriceEntity = new DoctorPriceEntity();
            doctorPriceEntity.setHospitalUuid(req.getHospitalUuid());
            doctorPriceEntity.setDoctorUuid(req.getDoctorUuid());
            doctorPriceEntity.setPrice(req.getPrice());
            doctorPriceService.insertSelective(doctorPriceEntity);
            for (WorkDayExt workDay : req.getWorks()){
                int day = workDay.getDay();
                if (CollectionUtils.isNotEmpty(workDay.getTimes())){
                    for (WorkTimeExt workTime : workDay.getTimes()){
                        DoctorOrderEntity doctorOrderEntity = new DoctorOrderEntity();
                        doctorOrderEntity.setDoctorUuid(req.getDoctorUuid());
                        doctorOrderEntity.setHospitalUuid(req.getHospitalUuid());
                        doctorOrderEntity.setDay(day);
                        doctorOrderEntity.setStartTime(workTime.getStartAndEndTime().get(0));
                        doctorOrderEntity.setEndTime(workTime.getStartAndEndTime().get(1));
                        doctorOrderEntity.setTotal(workTime.getTotal());
                        doctorOrderService.insertSelective(doctorOrderEntity);
                    }
                }
            }
        }
    }

    /**
     * 审批医生介绍
     * @param req
     */
    public void doctorIntroduce(DoctorIntroduceReq req) {
        Example exampleIntroduce = new Example(DoctorIntroduceEntity.class);
        Example.Criteria criteriaIntroduce = exampleIntroduce.createCriteria();
        criteriaIntroduce.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaIntroduce.andEqualTo("doctorUuid",req.getDoctorUuid());
        DoctorIntroduceEntity doctorIntroduceEntity = new DoctorIntroduceEntity();
        doctorIntroduceEntity.setStatus(req.getStatus());
        doctorIntroduceEntity.setReason(req.getReason());
        doctorIntroduceService.updateByExampleSelective(doctorIntroduceEntity,exampleIntroduce);
    }

    /**
     * 查看医生信息
     * @param req
     * @return
     */
    public DoctorShowRsp doctorShow(DoctorAddReq req) {
        DoctorShowRsp doctorShowRsp = new DoctorShowRsp();
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("uuid",req.getDoctorUuid());
        DoctorEntity doctorEntity = doctorService.selectByExample(exampleDoctor).get(0);
        BeanUtils.copyProperties(doctorEntity,doctorShowRsp);
        Example exampleDoctorOrder = new Example(DoctorOrderEntity.class);
        Example.Criteria criteriaDoctorOrder = exampleDoctorOrder.createCriteria();
        criteriaDoctorOrder.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctorOrder.andEqualTo("doctorUuid",req.getDoctorUuid());
        Example exampleDoctorPrice = new Example(DoctorPriceEntity.class);
        Example.Criteria criteriaDoctorPrice = exampleDoctorPrice.createCriteria();
        criteriaDoctorPrice.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctorPrice.andEqualTo("doctorUuid",req.getDoctorUuid());
        if (doctorEntity.getType().equals("doctor")){
            DoctorPriceEntity doctorPriceEntity = doctorPriceService.selectByExample(exampleDoctorPrice).get(0);
            doctorShowRsp.setDoctorUuid(doctorPriceEntity.getDoctorUuid());
            doctorShowRsp.setPrice(doctorPriceEntity.getPrice());
            List<DoctorOrderEntity> doctorOrderEntitys = doctorOrderService.selectByExample(exampleDoctorOrder);
            Map<Integer,List<DoctorOrderEntity>> map = doctorOrderEntitys.stream().collect(Collectors.groupingBy(DoctorOrderEntity::getDay));
            List<WorkDayExt> workDayExts = new ArrayList<>();
            map.forEach((key,value) -> {
                WorkDayExt workDayExt = new WorkDayExt();
                workDayExt.setDay(key);
                List<WorkTimeExt> workTimeExts = new ArrayList<>();
                value.forEach(doctorOrderEntity -> {
                    WorkTimeExt workTimeExt = new WorkTimeExt();
                    List<Date> dates = new ArrayList<>();
                    dates.add(doctorOrderEntity.getStartTime());
                    dates.add(doctorOrderEntity.getEndTime());
                    workTimeExt.setStartAndEndTime(dates);
                    workTimeExt.setTotal(doctorOrderEntity.getTotal());
                    workTimeExts.add(workTimeExt);
                });
                workDayExt.setTimes(workTimeExts);
                workDayExts.add(workDayExt);
            });
            doctorShowRsp.setWorks(workDayExts);
        }
        return doctorShowRsp;
    }

    /**
     * 改变医生状态
     * @param req
     */
    public void changeStatus(DoctorGetReq req) {
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("uuid",req.getDoctorUuid());
        DoctorEntity doctorEntity = new DoctorEntity();
        if (req.getStatus() != null) {
            doctorEntity.setStatus(req.getStatus());
        }
        //如果是删除医生，则将部门一栏固定 不在随部门修改而变动
        if (req.getIsDelete() != null) {
            if (req.getIsDelete() == 3) {
                exampleDoctor = new Example(DoctorEntity.class);
                criteriaDoctor = exampleDoctor.createCriteria();
                criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
                criteriaDoctor.andEqualTo("uuid",req.getDoctorUuid());
                String departmentCode = doctorService.selectByExample(exampleDoctor).get(0).getDepartment();
                Example exampleDepartment = new Example(DepartmentEntity.class);
                Example.Criteria criteriaDepartment = exampleDepartment.createCriteria();
                criteriaDepartment.andEqualTo("hospitalUuid",req.getHospitalUuid());
                criteriaDepartment.andEqualTo("code",departmentCode);
                doctorEntity.setDepartment(departmentService.selectByExample(exampleDepartment).get(0).getName());
            }
            doctorEntity.setIsDelete(req.getIsDelete());
        }
        doctorService.updateByExampleSelective(doctorEntity,exampleDoctor);
    }

    /**
     * 查找已经删除的医生
     * @param req
     * @return
     */
    public PageData<DoctorDeleteRsp> doctorDeleteList(DoctorDeleteListReq req) {
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("isDelete",3);
        if (StringUtils.isNotBlank(req.getDoctorName())) {
            criteriaDoctor.andLike("name","%" +req.getDoctorName() + "%");
        }
        if (StringUtils.isNotBlank(req.getDepartment())) {
            criteriaDoctor.andLike("department", "%" + req.getDepartment() + "%");
        }
        if (CollectionUtils.isNotEmpty(req.getTimes())) {
            criteriaDoctor.andBetween("updateTime",req.getTimes().get(0),req.getTimes().get(1));
        }
        exampleDoctor.setOrderByClause("update_time DESC");
        com.github.pagehelper.Page<DoctorDeleteRsp> page = PageHelper.startPage(
                req.getCurrentPage(), req.getPageSize()
        );
        List<DoctorDeleteRsp> list = doctorService.selectByExample(exampleDoctor).stream().map(s -> {
            DoctorDeleteRsp doctorDeleteRsp = new DoctorDeleteRsp();
            doctorDeleteRsp.setDoctorUuid(s.getUuid());
            doctorDeleteRsp.setDoctorName(s.getName());
            doctorDeleteRsp.setPictureUrl(s.getPicture());
            doctorDeleteRsp.setType(s.getType());
            doctorDeleteRsp.setDepartment(s.getDepartment());
            doctorDeleteRsp.setEndTime(s.getUpdateTime());
            doctorDeleteRsp.setSex(s.getSex());
            return doctorDeleteRsp;
        }).collect(Collectors.toList());
        int longs = ((Number) page.getTotal()).intValue();
        PageData<DoctorDeleteRsp> pageData = PageData.of(list,page.getPageNum(),page.getPageSize(),longs);
        return pageData;
    }

    /**
     * 获取医院定时任务信息
     * @param hospitalUuid
     * @return
     */
    public QuartzCronRsp getTaskMessage(String hospitalUuid) {
        Example exampleQuartzCron = new Example(QuartzCronEntity.class);
        Example.Criteria criteriaQuartzCron = exampleQuartzCron.createCriteria();
        criteriaQuartzCron.andEqualTo("hospitalUuid",hospitalUuid);
        QuartzCronEntity quartzCronEntity = quartzCronService.selectByExample(exampleQuartzCron).get(0);
        QuartzCronRsp quartzCronRsp = new QuartzCronRsp();
        BeanUtils.copyProperties(quartzCronEntity,quartzCronRsp);
        return quartzCronRsp;
    }

    /**
     * 编辑部门前检查
     * @param req
     * @return
     */
    public Boolean editDepartmentCheck(DepartmentReq req) {
        DepartmentEntity departmentEntity = departmentService.selectByPrimaryKey(req.getId());
        Example exampleDoctor = new Example(DoctorEntity.class);
        Example.Criteria criteriaDoctor = exampleDoctor.createCriteria();
        criteriaDoctor.andEqualTo("hospitalUuid",req.getHospitalUuid());
        criteriaDoctor.andEqualTo("department",departmentEntity.getCode());
        criteriaDoctor.andNotEqualTo("isDelete",3);
        List<DoctorEntity> list = doctorService.selectByExample(exampleDoctor);
        return CollectionUtils.isNotEmpty(list);
    }

    /**
     * 医院更新介绍
     * @param req
     */
    public void updateIntroduce(HospitalUpdateIntroduceReq req) {
        HospitalMessageEntity hospitalMessageEntity = new HospitalMessageEntity();
        if (StringUtils.isNotBlank(req.getHtml())) {
            //解码
            String result = StringEscapeUtils.unescapeHtml(req.getHtml());
            hospitalMessageEntity.setIntroduceHtml(result);
        }
        if (req.getStatus() != null) {
            hospitalMessageEntity.setStatus(req.getStatus());
        }
        if (req.getIsSell() != null) {
            hospitalMessageEntity.setIssell(req.getIsSell());
        }
        Example exampleHospitalIntroduce = new Example(HospitalMessageEntity.class);
        Example.Criteria criteriaIntroduce = exampleHospitalIntroduce.createCriteria();
        criteriaIntroduce.andEqualTo("uuid",req.getHospitalUuid());
        hospitalMessageService.updateByExampleSelective(hospitalMessageEntity,exampleHospitalIntroduce);
    }

    /**
     * 获取医院详细信息
     * @param req
     * @return
     */
    public HospitalMessageRsp getDetailMessage(HospitalMessageReq req) {
        Example exampleHospitalMessage = new Example(HospitalMessageEntity.class);
        Example.Criteria criteriaHospitalMessage = exampleHospitalMessage.createCriteria();
        criteriaHospitalMessage.andEqualTo("uuid",req.getHospitalUuid());
        HospitalMessageRsp hospitalMessageRsp = hospitalMessageService.selectByExample(exampleHospitalMessage).stream().map(s-> {
            HospitalMessageRsp tmp = new HospitalMessageRsp();
            BeanUtils.copyProperties(s,tmp);
            tmp.setIsSell(s.getIssell());
            return tmp;
        }).collect(Collectors.toList()).get(0);
        //转码
        String html = StringEscapeUtils.escapeHtml(hospitalMessageRsp.getIntroduceHtml());
        hospitalMessageRsp.setIntroduceHtml(html);
        return hospitalMessageRsp;
    }

    /**
     * 判断多个时间段是否冲突
     */
    public static boolean hasTimeConflict(List<TimeRangeExt> timeRanges) {
        Collections.sort(timeRanges, Comparator.comparing(TimeRangeExt::getStartTime));

        for (int i = 0; i < timeRanges.size() - 1; i++) {
            TimeRangeExt currentRange = timeRanges.get(i);
            TimeRangeExt nextRange = timeRanges.get(i + 1);

            if (currentRange.getEndTime().compareTo(nextRange.getStartTime()) > 0) {
                return true;
            }
        }
        return false;
    }
}
